import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { message } from 'antd';
import { WeaTableNew } from 'comsMobx';
import { WeaTab, WeaLocaleProvider, WeaButtonIcon } from 'ecCom';
import { AntdConfirm } from '../util';
import Edit from './Edit';

const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

@inject('settingStore', 'emailMenuStore')
@observer
class Label extends Component {
  static defaultProps = {
    prefixCls: 'email-setting-label',
  };

  constructor(props) {
    super(props);

    this.state = {
      editVisible: false,
    };
  }

  componentDidMount() {
    const {
      settingStore: { labelStore, setStoreState },
    } = this.props;
    let rightMenuDatas = [
      {
        key: 'refresh',
        icon: <i className="icon-coms-Update-synchronization" />,
        content: getLabel(197, '搜索'),
        onClick: () => labelStore.getMailLabel(),
      },
    ];
    setStoreState({ rightMenuDatas });
    labelStore.getMailLabel();
  }

  componentWillUnmount() {
    const {
      settingStore: { labelStore },
    } = this.props;
    labelStore.clear();
  }

  onOperatesClick = (record, index, operate) => {
    const {
      settingStore: { labelStore },
    } = this.props;
    const { operateUserMailLabel, getMailLabel } = labelStore;
    if (operate.index === '0') {
      // edit
      this.editLabel(record.randomFieldId);
    } else if (operate.index === '1') {
      // clear
      AntdConfirm(
        { content: getLabel(384431, '确定所有邮件都取消该标签标记吗？') },
        () => {
          let params = { operation: 'clear', id: record.randomFieldId };
          operateUserMailLabel(params).then((res) => {
            if (res.flag) {
              message.success(getLabel(384426, '清空成功'));
              getMailLabel('', true);
            } else {
              message.error(getLabel(384427, '清空失败'));
            }
          });
        },
      );
    } else if (operate.index === '2') {
      // delete
      this.batchDel(record.randomFieldId);
    }
  };

  editLabel = (id) => {
    const {
      settingStore: { labelStore },
    } = this.props;
    const {
      getEmailLabelCondition,
      setStoreState,
      getMailLabelBean,
    } = labelStore;
    getEmailLabelCondition('', () => {
      getMailLabelBean({ id });
      setStoreState({
        editTitle: getLabel(83264, '编辑标签'),
        isEdit: true,
        editId: id,
      });
      this.setState({ editVisible: true });
    });
  };

  batchDel = (id) => {
    const {
      settingStore: { labelStore },
    } = this.props;
    const { operateUserMailLabel, labelTable, getMailLabel } = labelStore;
    id = id || toJS(labelTable.selectedRowKeysAllPages).join();
    AntdConfirm('', () => {
      let params = { operation: 'del', id };
      operateUserMailLabel(params).then((res) => {
        if (res.flag) {
          message.success(getLabel(83472, '删除成功！'));
          getMailLabel();
          this.menuOpt();
        } else if (res.msg) {
          message.error(res.msg);
          getMailLabel();
          this.menuOpt();
        } else {
          message.error(getLabel(384401, '删除失败，请重试！'));
        }
      });
    });
  };

  getColumns = (columns) => {
    const { prefixCls } = this.props;
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex === 'name') {
          return (
            <React.Fragment
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_React.Fragment@z2tnfm@${record.randomFieldId}`}
            >
              <span
                className={`${prefixCls}-color`}
                style={{ background: record.color }}
              />
              <a
                className={`${prefixCls}-label`}
                title={text}
                onClick={() => this.editLabel(record.randomFieldId)}
              >
                {text}
              </a>
            </React.Fragment>
          );
        }
        return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />;
      };
      return newColumn;
    });
    return newColumns;
  };

  // 操作左侧 menu 数据
  menuOpt = () => {
    const { emailMenuStore } = this.props;
    emailMenuStore && emailMenuStore.getMenu();
  };

  onAddLabel = () => {
    this.refs.editLabel.wrappedInstance.addLabel(() =>
      this.setState({ editVisible: true }),
    );
  };

  onEditCancel = () => this.setState({ editVisible: false });

  onEditSubmit = () => {
    const {
      settingStore: { labelStore },
    } = this.props;
    labelStore.getMailLabel('', true);
    this.menuOpt();
  };

  render() {
    const {
      prefixCls,
      settingStore: { labelStore },
    } = this.props;
    const { labelTable } = labelStore;
    const tabButtons = [
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@hidruw@labeladd`}
        buttonType="add"
        type="primary"
        onClick={this.onAddLabel}
      />,
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@1sy78g@labeldel`}
        buttonType="del"
        type="primary"
        disabled={toJS(labelTable.selectedRowKeysAllPages).length === 0}
        onClick={() => this.batchDel()}
      />,
    ];
    return (
      <div className={prefixCls}>
        <WeaTab
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTab@vom2di`}
          datas={[{ title: getLabel(384430, '标签列表'), viewcondition: '1' }]}
          keyParam="viewcondition"
          buttons={tabButtons}
        />
        <WeaTable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTable@0udpm5`}
          comsWeaTableStore={labelTable}
          getColumns={this.getColumns}
          onOperatesClick={this.onOperatesClick}
          hasOrder
          needScroll
        />
        <Edit
          ecId={`${(this && this.props && this.props.ecId) || ''}_Edit@7952id`}
          ref="editLabel"
          visible={this.state.editVisible}
          onCancel={this.onEditCancel}
          onSubmit={this.onEditSubmit}
        />
      </div>
    );
  }
}

export default Label;
